package com.epam.productxslt.validation.validator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.epam.productxslt.validation.ValidationResult;
import com.epam.productxslt.validation.ValidationRule;




public class FormValidator {
	private HashMap<String, List<ValidationRule>> validationRules = new HashMap<String, List<ValidationRule>>();
	private HashMap<String, List<String>> errorMessages = new HashMap<String, List<String>>();
	private boolean validForm = true;
	
	public boolean validateInput(String name, String value) {
		List<ValidationRule> ruleList = validationRules.get(name);
		List<String> messages = new ArrayList<String>();
		boolean valid = true;
		for(ValidationRule rule : ruleList) {
			ValidationResult validationResult = rule.validate(value);
			if(!validationResult.isValid())	{
				valid = false;
				validForm = false;
				String message = validationResult.getMessage();
				messages.add(message);
			}
		}
		if(valid) {
			return true;
		}
		errorMessages.put(name, messages);
		return valid;
	}
	
	public void addValidationRule(String groupName, ValidationRule rule){
		List<ValidationRule> ruleList = validationRules.get(groupName);
		if(ruleList == null) {
			ruleList = new ArrayList<ValidationRule>();
			validationRules.put(groupName, ruleList);
		}
		ruleList.add(rule);
	}
	
	public List<ValidationRule> removeRuleGroup(String groupName) {
		return validationRules.remove(groupName);
	}
	
	public boolean removeValidationRule(String groupName, ValidationRule rule){
		boolean result = false;
		List<ValidationRule> ruleList = validationRules.get(groupName);
		if(ruleList != null) {
			result = ruleList.remove(rule);
		}
		return result;		
	}
	
	public void removeAllRules(){
		validationRules.clear();
	}
	
	public void reset(){
		errorMessages.clear();
		validForm = true;
	}
	
	public List<String> getMessageList(String inputName){
		List<String> messageList = errorMessages.get(inputName);		
		if(messageList != null){
			return new ArrayList<String>(messageList);
		} else {
			return null;
		}
	}

	
	public Map<String, List<String>> getErrorMessages(){
		Map<String, List<String>> errorMessagesCopy = new HashMap<String, List<String>>();
		Set<Map.Entry<String, List<String>>> errorMessagesEntry = errorMessages.entrySet();
		for(Map.Entry<String, List<String>> entry : errorMessagesEntry){
			List<String> messageListCopy = new ArrayList<String>(entry.getValue());
			errorMessagesCopy.put(entry.getKey(), messageListCopy);
		}
		return errorMessages;		
	}
	
	
	public boolean isValidForm() {
		return validForm;
	}
	
}
